import zhipuai
import json
import logging
from typing import Dict, List, Optional, Any
from config import Config

logger = logging.getLogger(__name__)

class ZhipuAIClient:
    """智谱AI客户端，用于与大模型进行交互"""
    
    def __init__(self):
        self.api_key = Config.ZHIPUAI_API_KEY
        self.model = Config.ZHIPUAI_MODEL
        self.client = None
        self._init_client()
    
    def _init_client(self):
        """初始化客户端，兼容不同版本的API"""
        try:
            # 尝试新版本API (zhipuai >= 1.0.0)
            self.client = zhipuai.ZhipuAI(api_key=self.api_key)
            logger.info("使用新版本ZhipuAI API")
            self.api_version = "new"
        except AttributeError:
            try:
                # 尝试旧版本API (zhipuai < 1.0.0)
                self.client = zhipuai.zhipuai(api_key=self.api_key)
                logger.info("使用旧版本zhipuai API")
                self.api_version = "old"
            except Exception as e:
                logger.error(f"无法初始化zhipuai客户端: {e}")
                # 创建一个模拟客户端用于测试
                self.client = None
                self.api_version = "mock"
                logger.warning("使用模拟客户端，请检查API密钥配置")
        
    def chat_completion(self, messages: List[Dict[str, str]], 
                       temperature: float = 0.7,
                       max_tokens: int = 2000) -> Dict[str, Any]:
        """
        与智谱AI进行对话
        
        Args:
            messages: 消息列表，格式为 [{"role": "user", "content": "..."}]
            temperature: 温度参数，控制回答的随机性
            max_tokens: 最大token数
            
        Returns:
            AI回复的字典
        """
        if self.client is None:
            return {
                "content": "AI服务未正确初始化，请检查API密钥配置。",
                "error": "Client not initialized"
            }
        
        try:
            if self.api_version == "new":
                # 新版本API
                response = self.client.chat.completions.create(
                    model=self.model,
                    messages=messages,
                    temperature=temperature,
                    max_tokens=max_tokens
                )
                
                return {
                    "content": response.choices[0].message.content,
                    "usage": {
                        "prompt_tokens": response.usage.prompt_tokens,
                        "completion_tokens": response.usage.completion_tokens,
                        "total_tokens": response.usage.total_tokens
                    }
                }
            elif self.api_version == "old":
                # 旧版本API
                # 将消息列表转换为单个prompt
                prompt = self._messages_to_prompt(messages)
                response = self.client.invoke(
                    model=self.model,
                    prompt=prompt,
                    temperature=temperature,
                    top_p=0.7,
                    max_tokens=max_tokens
                )
                
                return {
                    "content": response.get("data", {}).get("text", ""),
                    "usage": {
                        "prompt_tokens": response.get("usage", {}).get("prompt_tokens", 0),
                        "completion_tokens": response.get("usage", {}).get("completion_tokens", 0),
                        "total_tokens": response.get("usage", {}).get("total_tokens", 0)
                    }
                }
            else:
                # 模拟响应
                return {
                    "content": "这是一个模拟的AI响应，请配置正确的API密钥。",
                    "usage": {"prompt_tokens": 0, "completion_tokens": 0, "total_tokens": 0}
                }
                
        except Exception as e:
            logger.error(f"智谱AI调用失败: {str(e)}")
            return {
                "content": "抱歉，AI服务暂时不可用，请稍后再试。",
                "error": str(e)
            }
    
    def _messages_to_prompt(self, messages: List[Dict[str, str]]) -> str:
        """将消息列表转换为单个prompt字符串"""
        prompt = ""
        for message in messages:
            role = message.get("role", "user")
            content = message.get("content", "")
            if role == "system":
                prompt += f"系统: {content}\n"
            elif role == "user":
                prompt += f"用户: {content}\n"
            elif role == "assistant":
                prompt += f"助手: {content}\n"
        return prompt.strip()
    
    def analyze_text(self, text: str, analysis_type: str = "general") -> Dict[str, Any]:
        """
        文本分析
        
        Args:
            text: 待分析的文本
            analysis_type: 分析类型 (general, sentiment, difficulty, topic)
            
        Returns:
            分析结果
        """
        prompts = {
            "general": f"请分析以下文本的内容、结构和质量：\n\n{text}\n\n请从以下几个方面进行分析：\n1. 主要内容\n2. 写作质量\n3. 逻辑结构\n4. 改进建议",
            
            "sentiment": f"请分析以下文本的情感倾向和态度：\n\n{text}\n\n请给出：\n1. 情感倾向（积极/消极/中性）\n2. 情感强度（1-10分）\n3. 主要情感词汇\n4. 情感分析理由",
            
            "difficulty": f"请评估以下学习内容或作业的难度等级：\n\n{text}\n\n请给出：\n1. 难度等级（初级/中级/高级）\n2. 难度评分（1-10分）\n3. 适合的学习者水平\n4. 难点分析",
            
            "topic": f"请识别以下文本的主要主题和知识点：\n\n{text}\n\n请给出：\n1. 主要主题\n2. 相关知识点\n3. 学科分类\n4. 学习建议"
        }
        
        prompt = prompts.get(analysis_type, prompts["general"])
        
        messages = [
            {"role": "system", "content": "你是一个专业的文本分析助手，擅长分析学习内容和作业质量。"},
            {"role": "user", "content": prompt}
        ]
        
        response = self.chat_completion(messages, temperature=0.3)
        return response
    
    def generate_learning_recommendations(self, 
                                        student_profile: Dict[str, Any],
                                        learning_history: List[Dict[str, Any]]) -> Dict[str, Any]:
        """
        生成个性化学习推荐
        
        Args:
            student_profile: 学生档案信息
            learning_history: 学习历史记录
            
        Returns:
            推荐结果
        """
        # 构建学生画像
        profile_summary = f"""
        学生信息：
        - 年级：{student_profile.get('grade', '未知')}
        - 专业：{student_profile.get('major', '未知')}
        - 学习偏好：{student_profile.get('learning_style', '未知')}
        """
        
        # 构建学习历史摘要
        history_summary = "学习历史：\n"
        for record in learning_history[-10:]:  # 最近10条记录
            history_summary += f"- {record.get('name', '未知课程')}: 进度{record.get('progress', 0)}%, 成绩{record.get('score', 0)}分\n"
        
        prompt = f"""
        基于以下学生信息，请生成个性化的学习推荐：
        
        {profile_summary}
        
        {history_summary}
        
        请从以下几个方面给出推荐：
        1. 推荐课程（3-5门）
        2. 推荐学习资源（5-8个）
        3. 学习建议和策略
        4. 重点关注的知识点
        5. 学习时间安排建议
        
        请以JSON格式返回结果。
        """
        
        messages = [
            {"role": "system", "content": "你是一个专业的个性化学习推荐助手，擅长基于学生画像和学习历史生成精准的学习建议。"},
            {"role": "user", "content": prompt}
        ]
        
        response = self.chat_completion(messages, temperature=0.5)
        
        # 尝试解析JSON响应
        try:
            content = response.get("content", "")
            if "```json" in content:
                json_start = content.find("```json") + 7
                json_end = content.find("```", json_start)
                json_str = content[json_start:json_end].strip()
                return json.loads(json_str)
            else:
                # 如果没有JSON格式，返回原始内容
                return {
                    "recommendations": content,
                    "format": "text"
                }
        except json.JSONDecodeError:
            return {
                "recommendations": response.get("content", "无法生成推荐"),
                "format": "text"
            }
    
    def answer_question(self, question: str, context: Optional[str] = None, 
                       subject: str = "general") -> Dict[str, Any]:
        """
        智能问答
        
        Args:
            question: 学生问题
            context: 上下文信息
            subject: 学科领域
            
        Returns:
            回答结果
        """
        system_prompts = {
            "math": "你是一个专业的数学老师，擅长解答数学问题，包括代数、几何、微积分等各个领域。请用清晰易懂的方式解释概念和解题步骤。",
            "physics": "你是一个专业的物理老师，擅长解答物理问题，包括力学、电磁学、热学等各个领域。请用生动的例子和清晰的逻辑来解释物理概念。",
            "computer_science": "你是一个专业的计算机科学老师，擅长解答编程、算法、数据结构等问题。请提供详细的代码示例和解释。",
            "general": "你是一个专业的学习助手，擅长解答各种学科的问题。请用通俗易懂的方式回答问题，并提供相关的学习资源建议。"
        }
        
        system_prompt = system_prompts.get(subject, system_prompts["general"])
        
        user_content = question
        if context:
            user_content = f"上下文：{context}\n\n问题：{question}"
        
        messages = [
            {"role": "system", "content": system_prompt},
            {"role": "user", "content": user_content}
        ]
        
        response = self.chat_completion(messages, temperature=0.7)
        
        # 提取相关资源建议
        content = response.get("content", "")
        related_resources = self._extract_related_resources(content)
        
        return {
            "answer": content,
            "related_resources": related_resources,
            "confidence": self._estimate_confidence(content),
            "usage": response.get("usage", {})
        }
    
    def _extract_related_resources(self, content: str) -> List[str]:
        """从回答中提取相关资源建议"""
        resources = []
        lines = content.split('\n')
        
        for line in lines:
            if any(keyword in line.lower() for keyword in ['推荐', '建议', '资源', '参考', '学习']):
                if '：' in line or ':' in line:
                    resource = line.split('：')[-1] if '：' in line else line.split(':')[-1]
                    resources.append(resource.strip())
        
        return resources[:5]  # 最多返回5个资源
    
    def _estimate_confidence(self, content: str) -> float:
        """估算回答的置信度"""
        # 简单的置信度估算逻辑
        confidence_indicators = [
            "我确定", "毫无疑问", "明确", "肯定", "一定"
        ]
        
        uncertainty_indicators = [
            "可能", "也许", "大概", "不确定", "需要进一步", "建议"
        ]
        
        content_lower = content.lower()
        
        confidence_score = 0.7  # 基础置信度
        
        for indicator in confidence_indicators:
            if indicator in content_lower:
                confidence_score += 0.1
        
        for indicator in uncertainty_indicators:
            if indicator in content_lower:
                confidence_score -= 0.1
        
        return max(0.1, min(1.0, confidence_score))
    
    def batch_analyze_assignments(self, assignments: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
        """
        批量分析作业
        
        Args:
            assignments: 作业列表
            
        Returns:
            分析结果列表
        """
        results = []
        
        for assignment in assignments:
            try:
                content = assignment.get('content', '')
                analysis = self.analyze_text(content, "general")
                
                results.append({
                    "assignment_id": assignment.get('id'),
                    "analysis": analysis,
                    "score_suggestion": self._suggest_score(analysis.get('content', '')),
                    "feedback": self._generate_feedback(analysis.get('content', ''))
                })
            except Exception as e:
                logger.error(f"分析作业失败: {str(e)}")
                results.append({
                    "assignment_id": assignment.get('id'),
                    "error": str(e)
                })
        
        return results
    
    def _suggest_score(self, analysis: str) -> float:
        """基于分析结果建议分数"""
        # 简单的分数建议逻辑
        if "优秀" in analysis or "很好" in analysis:
            return 90.0
        elif "良好" in analysis or "不错" in analysis:
            return 80.0
        elif "一般" in analysis or "中等" in analysis:
            return 70.0
        elif "较差" in analysis or "需要改进" in analysis:
            return 60.0
        else:
            return 75.0
    
    def _generate_feedback(self, analysis: str) -> str:
        """基于分析结果生成反馈"""
        prompt = f"""
        基于以下分析结果，请生成具体的改进建议和鼓励性反馈：
        
        {analysis}
        
        请从以下几个方面给出反馈：
        1. 优点和亮点
        2. 需要改进的地方
        3. 具体的改进建议
        4. 鼓励性的话语
        """
        
        messages = [
            {"role": "system", "content": "你是一个专业的教师，擅长给学生提供建设性的反馈和建议。"},
            {"role": "user", "content": prompt}
        ]
        
        response = self.chat_completion(messages, temperature=0.5)
        return response.get("content", "请继续努力，相信你会做得更好！")